﻿// ***********************************************************************
// Assembly         : NIMServerApi
// Author           : Walter
// Created          : 11-15-2016
//
// Last Modified By : Walter
// Last Modified On : 11-15-2016
// ***********************************************************************
// <copyright file="CheckSumBuilder.cs" company="">
//     Copyright ©  2016
// </copyright>
// <summary></summary>
// ***********************************************************************

using System;
using System.Security.Cryptography;
using System.Text;

namespace NIMServerApi.Commons
{
    /// <summary>
    /// Class CheckSumBuilder.
    /// </summary>
    public class CheckSumBuilder
    {
        /// <summary>
        /// Gets the check sum.
        /// </summary>
        /// <param name="appSecret">The application secret.</param>
        /// <param name="nonce">The nonce.</param>
        /// <param name="curTime">The current time.</param>
        /// <returns>System.String.</returns>
        public static string GetCheckSum(string appSecret, string nonce, string curTime)
        {
            return EncryptToSHA1(string.Concat(appSecret, nonce, curTime));
        }

        /// <summary>
        /// Gets the md5.
        /// </summary>
        /// <param name="requestBody">The request body.</param>
        /// <returns>System.String.</returns>
        public static string GetMD5(string requestBody)
        {
            return EncryptToMD5(requestBody);
        }


        #region 获取由SHA1加密的字符串
        static string EncryptToSHA1(string str)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
            byte[] str1 = Encoding.UTF8.GetBytes(str);
            byte[] str2 = sha1.ComputeHash(str1);
            sha1.Clear();
            (sha1 as IDisposable).Dispose();
            return GetFormattedText(str2);
        }
        #endregion

        #region 获取由MD5加密的字符串
        static string EncryptToMD5(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] str1 = Encoding.UTF8.GetBytes(str);
            byte[] str2 = md5.ComputeHash(str1, 0, str1.Length);
            md5.Clear();
            (md5 as IDisposable).Dispose();
            return GetFormattedText(str2);
        }
        #endregion

        private static String GetFormattedText(byte[] bytes)
        {
            int len = bytes.Length;
            StringBuilder buf = new StringBuilder(len * 2);
            for (int j = 0; j < len; j++)
            {
                buf.Append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
                buf.Append(HEX_DIGITS[bytes[j] & 0x0f]);
            }
            return buf.ToString();
        }
        private static char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    }
}